package com.ushine.web.security.handler;

import com.ushine.web.base.facade.IUserRedisFacade;
import com.ushine.web.security.jwt.JwtProperties;
import com.ushine.web.security.jwt.JwtTokenUtil;
import com.ushine.web.security.redis.RedisTokenClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: yls
 * @Date 2022/2/15 10:10
 * @Description: 注销的时候做的一些操作
 * @Version 1.0
 **/
@Slf4j
@Component
public class FightLogoutHandler implements LogoutHandler {


    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Resource
    private JwtProperties jwtProperties;

    @Resource
    private RedisTokenClient redisTokenClient;

    @Resource
    private IUserRedisFacade userRedisFacade;

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse httpServletResponse, Authentication authentication) {
        String header = jwtProperties.getHeader();
        String token = request.getHeader(header);
        // 规定前缀
        String prefix = jwtProperties.getPrefix();
        if (StringUtils.isBlank(prefix)) {
            // 没有前缀指定，不作任何操作
        } else if (StringUtils.isNotEmpty(token) && token.startsWith(prefix)) {
            token = token.substring(jwtProperties.getPrefix().length());
        } else {
            // 不按规范,不允许通过验证
            return;
        }
        // 获取用户信息
        String username = jwtTokenUtil.getUsernameFromToken(token);
        // 注销成功后将【token】删除
        redisTokenClient.getUserBucket(username).delete();

        /*
         * 删除缓存中的权限信息
         */
        userRedisFacade.deleteUserInfo(username);


        log.info("注销成功：{}", redisTokenClient.getUserToken(username));
    }
}
